<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | 王勇程 <laughskydragon@qq.com>                         |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\admin\logic;

use app\common\logic\User as CommonUser;

/**
 * 用户管理逻辑
 */
class User extends AdminBase
{
    
    public static $commonUserLogic = null;
    
    /**
     * 基类初始化
     */
    public function __construct()
    {
        // 执行父类构造方法
        parent::__construct();
        
        empty(static::$commonUserLogic) && static::$commonUserLogic = new CommonUser();
    }
    /**
     * 获取用户列表搜索条件
     * @param array $data 搜索参数
     * @return array
     */
    public function getWhere($data = [])
    {
        return static::$commonUserLogic->getWhere($data);
    }
    
    /**
     * 获取用户统计数据
     */
    public function getUserStats()
    {
        // 总用户数（排除已删除）
        $totalUsers = $this->modelUser->stat(['status' => ['neq', DATA_DELETE]], 'count');
        
        // 今日新增用户
        $todayStart = strtotime(date('Y-m-d 00:00:00'));
        $todayEnd = strtotime(date('Y-m-d 23:59:59'));
        $todayNewUsers = $this->modelUser->stat([
            'create_time' => ['between', [$todayStart, $todayEnd]],
            'status' => ['neq', DATA_DELETE]
        ], 'count');
        
        // VIP用户数（有效VIP用户）
        $vipUsers = $this->modelUser->stat([
            'vip_level' => ['>', 0],
            'vip_expire_time' => ['>', time()],
            'status' => ['neq', DATA_DELETE]
        ], 'count');
        
        // 活跃用户数（7天内登录）
        $activeUsers = $this->modelUser->stat([
            'last_login_time' => ['>', time() - 7 * 86400],
            'status' => ['neq', DATA_DELETE]
        ], 'count');
        
        return [
            'total_users' => $totalUsers,
            'today_new_users' => $todayNewUsers,
            'vip_users' => $vipUsers,
            'active_users' => $activeUsers
        ];
    }

    /**
     * 获取用户列表
     */
    public function getUserList($where = [], $field = true, $order = 'create_time desc', $paginate = DB_LIST_ROWS)
    {
        // 排除已删除的用户
        $where[DATA_STATUS_NAME] = ['neq', DATA_DELETE];
        
        return $this->modelUser->getList($where, $field, $order, $paginate);
    }
    
    /**
     * 获取用户信息
     */
    public function getUserInfo($where = [])
    {
        return $this->modelUser->getInfo($where);
    }
    
    /**
     * 用户添加
     */
    public function userAdd($data = [])
    {
        $url = url('userList');
        
        $validate_result = $this->validateUser->scene('add')->check($data);
        
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateUser->getError()];
        }
        
        // 密码加密
        if (!empty($data['password'])) {
            $data['password'] = data_md5_key($data['password']);
        }
        
        $data['create_time'] = time();
        $data['update_time'] = time();
        
        $result = $this->modelUser->setInfo($data);
        
        $result && action_log('新增', '新增用户，昵称：' . $data['nickname']);
        
        return $result ? [RESULT_SUCCESS, '新增成功', $url] : [RESULT_ERROR, $this->modelUser->getError()];
    }
    
    /**
     * 用户编辑
     */
    public function userEdit($data = [])
    {
        $url = url('userList');
        
        $validate_result = $this->validateUser->scene('edit')->check($data);
        
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateUser->getError()];
        }
        
        // 密码加密
        if (!empty($data['password'])) {
            $data['password'] = data_md5_key($data['password']);
        } else {
            unset($data['password']);
        }
        
        $data['update_time'] = time();
        
        $result = $this->modelUser->updateInfo(['id' => $data['id']], $data);
        
        $result && action_log('编辑', '编辑用户，id：' . $data['id']);
        
        return $result ? [RESULT_SUCCESS, '编辑成功', $url] : [RESULT_ERROR, $this->modelUser->getError()];
    }
    
    /**
     * 用户删除
     */
    public function userDel($data = [])
    {
        $url = url('userList');
        
        $id = $data['id'] ?? 0;
        
        if (!$id) {
            return [RESULT_ERROR, '参数错误'];
        }
        
        $result = $this->modelUser->deleteInfo(['id' => $id]);
        
        $result && action_log('删除', '删除用户，id：' . $id);
        
        return $result ? [RESULT_SUCCESS, '删除成功', $url] : [RESULT_ERROR, $this->modelUser->getError()];
    }
    
    /**
     * 用户状态切换
     */
    public function userStatus($data = [])
    {
        $url = url('userList');
        
        $id = $data['id'] ?? 0;
        $status = $data['status'] ?? 0;
        
        if (!$id) {
            return [RESULT_ERROR, '参数错误'];
        }
        
        $result = $this->modelUser->updateInfo(['id' => $id], ['status' => $status, 'update_time' => time()]);
        
        $result && action_log('状态', '用户状态切换，id：' . $id . '，状态：' . $status);
        
        return $result ? [RESULT_SUCCESS, '操作成功', $url] : [RESULT_ERROR, $this->modelUser->getError()];
    }
    
    /**
     * 用户导出
     */
    public function exportUserList($where = [])
    {
        $list = $this->getUserList($where, true, 'create_time desc', false);
        
        $titles = "ID,昵称,手机号,VIP等级,状态,注册时间";
        $keys   = "id,nickname,mobile,vip_level,status,create_time";
        
        action_log('导出', '导出用户列表');
        
        export_excel($titles, $keys, $list, '用户列表');
    }
    
    /**
     * 用户VIP管理
     */
    public function userVipManage($data = [])
    {
        $url = url('userList');
        
        $userId = $data['id'];
        $vipLevel = $data['vip_level'] ?? 0;
        $startTime = $data['vip_start_time'] ?? null;
        $expireTime = $data['vip_expire_time'] ?? null;
        
        // 转换时间格式为时间戳
        if ($startTime) {
            $startTime = strtotime($startTime);
        }
        if ($expireTime) {
            $expireTime = strtotime($expireTime);
        }
        
        // 更新用户VIP信息
        $updateData = [
            'vip_level' => $vipLevel,
            'update_time' => time()
        ];
        
        if ($startTime) {
            $updateData['vip_start_time'] = $startTime;
        }
        if ($expireTime) {
            $updateData['vip_expire_time'] = $expireTime;
        }
        
        $result = $this->modelUser->updateInfo(['id' => $userId], $updateData);
        
        $result && action_log('VIP管理', '用户VIP管理，id：' . $userId . '，VIP等级：' . $vipLevel);
        
        return $result ? [RESULT_SUCCESS, 'VIP管理成功', $url] : [RESULT_ERROR, $this->modelUser->getError()];
    }
    
    /**
     * 用户积分管理
     */
    public function userPointsManage($data = [])
    {
        $url = url('userList');
        
        $userId = $data['id'];
        $points = $data['points'];
        $type = $data['type']; // add 或 subtract
        $description = $data['description'] ?? '管理员操作';
        
        $user = $this->modelUser->getInfo(['id' => $userId]);
        if (!$user) {
            return [RESULT_ERROR, '用户不存在'];
        }
        
        $newPoints = $type == 'add' ? $user['total_points'] + $points : $user['total_points'] - $points;
        $newPoints = max(0, $newPoints); // 积分不能为负数
        
        // 更新用户积分
        $result = $this->modelUser->updateInfo(['id' => $userId], [
            'total_points' => $newPoints,
            'update_time' => time()
        ]);
        
        if ($result) {
            // 记录积分变动
            $this->modelPointsRecord->setInfo([
                'user_id' => $userId,
                'type' => $type == 'add' ? 'admin_add' : 'admin_subtract',
                'points' => $type == 'add' ? $points : -$points,
                'description' => $description,
                'create_time' => time(),
                'update_time' => time()
            ]);
            
            action_log('积分管理', '用户积分管理，id：' . $userId . '，操作：' . $type . '，积分：' . $points);
        }
        
        return $result ? [RESULT_SUCCESS, '积分管理成功', $url] : [RESULT_ERROR, $this->modelUser->getError()];
    }
    
    /**
     * 生成邀请码
     */
    public function generateInviteCode($data = [])
    {
        $url = url('userList');
        
        $userId = $data['id'] ?? 0;
        
        if (!$userId) {
            return [RESULT_ERROR, '参数错误'];
        }
        
        // 生成唯一邀请码
        do {
            $inviteCode = strtoupper(substr(md5(uniqid()), 0, 8));
            $exists = $this->modelUser->getInfo(['invite_code' => $inviteCode]);
        } while ($exists);
        
        $result = $this->modelUser->updateInfo(['id' => $userId], [
            'invite_code' => $inviteCode,
            'update_time' => time()
        ]);
        
        $result && action_log('邀请码', '生成邀请码，用户id：' . $userId . '，邀请码：' . $inviteCode);
        
        return $result ? [RESULT_SUCCESS, '邀请码生成成功', $url] : [RESULT_ERROR, $this->modelUser->getError()];
    }
}